package com.kingdee.pda.plugins.http.common;

import android.util.Log;

import com.kingdee.pda.plugins.http.common.coreprogress.ProgressHelper;
import com.kingdee.pda.plugins.http.common.coreprogress.ProgressListener;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * http下载工具类
 * @author Zhuhuahua
 * @date 2016/12/22 11:58
 */
public class HttpDownloadInvoker {
    private static final byte[] LOCKER = new byte[0];
    private static HttpDownloadInvoker mInstance;
    private OkHttpClient mOkHttpClient;
    public enum  HttpCode{
        CODE_FILENOEXIST("001");//文件不存在
        private String errorCode;

        HttpCode(String errorCode) {
            this.errorCode = errorCode;
        }
        /**
         * messageId code
         * @return
         */
        public String errorCode(){
            return errorCode;
        }
    }
    private HttpDownloadInvoker() {
        okhttp3.OkHttpClient.Builder ClientBuilder=new okhttp3.OkHttpClient.Builder();
        ClientBuilder.readTimeout(30, TimeUnit.SECONDS);//读取超时
        ClientBuilder.connectTimeout(10, TimeUnit.SECONDS);//连接超时
        ClientBuilder.writeTimeout(60, TimeUnit.SECONDS);//写入超时
        mOkHttpClient=ClientBuilder.build();
    }

    public static HttpDownloadInvoker getInstance() {
        if (mInstance == null) {
            synchronized (LOCKER) {
                if (mInstance == null) {
                    mInstance = new HttpDownloadInvoker();
                }
            }
        }
        return mInstance;
    }

    /**
     * http下载功能
     * @param fileUrl
     * @param progressListener
     */
    public void  httpDownLoadFile(String lcoalUrl,String fileUrl, ProgressListener progressListener){
        //构造请求
        Request request= new Request.Builder()
                .url(fileUrl)
                .build();
        //包装Response使其支持进度回调
        ProgressHelper.addProgressResponseListener(mOkHttpClient, progressListener,lcoalUrl).newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("TAG", "error ", e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.e("TAG", response.body().string());
            }

        });
    }


}
